package com.hexus.eve.actions.security;

import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.hexus.eve.entities.security.Authorities;
import com.hexus.eve.entities.security.SecurityGroup;
import com.opensymphony.xwork2.ActionSupport;

public class UpdateGroup extends ActionSupport {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private SessionFactory sessionFactory;
	private Integer securityGroupId;
	private String name;
	private List<String> authorities;	
	
	@Override
	public String execute() throws Exception {
		HibernateTemplate ht = new HibernateTemplate(sessionFactory);
		SecurityGroup securityGroup;
		
		//Update or creation of a new item
		if(securityGroupId != null) {
			securityGroup = ht.get(SecurityGroup.class, securityGroupId);
		} else {
			securityGroup = new SecurityGroup();
		}
		
		//Updating fields
		securityGroup.setName(name);
		securityGroup.getAuthorities().clear();
		securityGroup.getAuthorities().addAll(authorities);
		if(securityGroupId != null) {
			ht.update(securityGroup);
		} else {
			ht.save(securityGroup);			
		}
		return SUCCESS;
	}

	public Integer getSecurityGroupId() {
		return securityGroupId;
	}

	public void setSecurityGroupId(String securityGroupId) {
		if(securityGroupId != null && !"".equals(securityGroupId))
			this.securityGroupId = Integer.parseInt(securityGroupId);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<Authorities> getAuthorities() {
		return Arrays.asList(Authorities.values());
	}

	public void setAuthorities(List<String> authorities) {
		this.authorities = authorities;
	}
	
	@Override
	public void validate() {
		if(authorities.size() == 0) {
			ResourceBundle bundle = ResourceBundle.getBundle ("global", getLocale());
			addFieldError("authorities", bundle.getString("validation.not.empty"));
		}
	}	
}
